<template>
  <div class="sql-item">
    <div class="sql-header">
      <span class="sql-index" :class="{ 'batch-operation': statement.isBatch }">
        SQL语句 {{ index + 1 }} ({{ paramInfo }})
        <span v-if="statement.isBatch" class="batch-badge">BATCH</span>
      </span>
      <div>
        <button class="copy-btn" @click="copyToClipboard(statement.processed)">
          复制原始SQL
        </button>
        <button class="copy-btn" @click="copyFormattedSQL">
          复制格式化SQL
        </button>
        <button v-if="isSelectQuery" class="query-btn" @click="executeQuery">
          查询
        </button>
        <button v-if="isSelectQuery" class="ai-btn" @click="openAiAnalysis">
          🤖 AI分析
        </button>
      </div>
    </div>
    <div class="sql-content" v-html="displaySQL"></div>
    
    <!-- 查询结果 -->
    <QueryResult
      v-if="showResult"
      :loading="queryLoading"
      :error="queryError"
      :result="queryResult"
      @close="showResult = false"
    />
    
    <!-- AI分析对话框 -->
    <AiAnalysisDialog
      :visible="showAiAnalysis"
      :loading="aiAnalysisLoading"
      :error="aiAnalysisError"
      :analysis-result="aiAnalysisResult"
      @close="closeAiAnalysis"
    />
  </div>
</template>

<script>
import { formatSQL, highlightSQL } from '../utils/sqlFormatter'
import QueryResult from './QueryResult.vue'
import AiAnalysisDialog from './AiAnalysisDialog.vue'
import api from '../utils/api'
import configManager from '../utils/config'

export default {
  name: 'SqlItem',
  components: {
    QueryResult,
    AiAnalysisDialog
  },
  props: {
    statement: {
      type: Object,
      required: true
    },
    index: {
      type: Number,
      required: true
    },
    isFormatted: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      showResult: false,
      queryLoading: false,
      queryError: null,
      queryResult: null,
      // AI分析相关状态
      showAiAnalysis: false,
      aiAnalysisLoading: false,
      aiAnalysisError: null,
      aiAnalysisResult: null
    }
  },
  computed: {
    paramInfo() {
      if (this.statement.isBatch) {
        return `批量操作 - ${this.statement.batchCount}条记录`
      }
      const count = this.statement.parameters.length
      return count === 0 ? '无参数' : `${count}个参数`
    },
    displaySQL() {
      if (this.isFormatted) {
        const formatted = formatSQL(this.statement.processed)
        return highlightSQL(formatted)
      } else {
        return this.escapeHtml(this.statement.processed)
      }
    },
    isSelectQuery() {
      const sql = this.statement.processed.trim().toUpperCase()
      return sql.startsWith('SELECT')
    }
  },
  methods: {
    escapeHtml(text) {
      const div = document.createElement('div')
      div.textContent = text
      return div.innerHTML
    },
    
    async copyToClipboard(text) {
      try {
        await navigator.clipboard.writeText(text)
        this.$el.querySelector('.copy-btn').textContent = '已复制'
        setTimeout(() => {
          this.$el.querySelector('.copy-btn').textContent = '复制原始SQL'
        }, 2000)
      } catch (err) {
        // 降级方案
        const textArea = document.createElement('textarea')
        textArea.value = text
        document.body.appendChild(textArea)
        textArea.select()
        document.execCommand('copy')
        document.body.removeChild(textArea)
      }
    },
    
    async copyFormattedSQL() {
      const formatted = formatSQL(this.statement.processed)
      try {
        await navigator.clipboard.writeText(formatted)
        const btn = this.$el.querySelectorAll('.copy-btn')[1]
        btn.textContent = '已复制'
        setTimeout(() => {
          btn.textContent = '复制格式化SQL'
        }, 2000)
      } catch (err) {
        // 降级方案
        const textArea = document.createElement('textarea')
        textArea.value = formatted
        document.body.appendChild(textArea)
        textArea.select()
        document.execCommand('copy')
        document.body.removeChild(textArea)
      }
    },
    
    async executeQuery() {
      // 检查数据库配置
      if (!configManager.isDbConfigValid()) {
        alert('请先配置数据库连接信息')
        return
      }
      
      this.showResult = true
      this.queryLoading = true
      this.queryError = null
      this.queryResult = null
      
      try {
        const dbConfig = configManager.getDbConfig()
        const result = await api.executeQuery(this.statement.processed, dbConfig)
        
        if (result.success) {
          this.queryResult = result.data
        } else {
          this.queryError = result.message || '查询失败'
        }
      } catch (error) {
        this.queryError = error.message
      } finally {
        this.queryLoading = false
      }
    },
    
    // AI分析相关方法
    async openAiAnalysis() {
      // 检查数据库配置
      if (!configManager.isDbConfigValid()) {
        alert('请先配置数据库连接信息')
        return
      }
      
      this.showAiAnalysis = true
      this.aiAnalysisLoading = true
      this.aiAnalysisError = null
      this.aiAnalysisResult = null
      
      try {
        const dbConfig = configManager.getDbConfig()
        const result = await api.analyzeExecutionPlan(this.statement.processed, dbConfig)
        
        if (result.success) {
          this.aiAnalysisResult = result.data
        } else {
          this.aiAnalysisError = result.message || 'AI分析失败'
        }
      } catch (error) {
        this.aiAnalysisError = error.message
      } finally {
        this.aiAnalysisLoading = false
      }
    },
    
    closeAiAnalysis() {
      this.showAiAnalysis = false
      this.aiAnalysisError = null
      this.aiAnalysisResult = null
    },
    
    // 获取查询结果用于ER图分析（支持所有SQL类型，最多10条数据）
    getQueryResultForEr() {
      const sqlType = this.getSQLType()
      
      // 对于SELECT查询，返回查询结果数据
      if (sqlType === 'SELECT' && this.queryResult) {
        if (this.queryResult.columns && this.queryResult.rows) {
          return {
            columns: this.queryResult.columns.map(col => ({
              name: col.name,
              comment: col.comment || '',
              dataType: col.dataType || ''
            })),
            // 限制最多10条数据
            rows: this.queryResult.rows.slice(0, 10),
            total: this.queryResult.total || 0,
            hasMore: this.queryResult.rows && this.queryResult.rows.length > 10
          }
        }
        return null
      }
      
      // 对于INSERT/UPDATE/DELETE等非查询语句，返回执行结果信息
      if (['INSERT', 'UPDATE', 'DELETE'].includes(sqlType)) {
        if (this.queryResult) {
          return {
            columns: [
              { name: 'sql_type', comment: 'SQL类型', dataType: 'VARCHAR' },
              { name: 'affected_rows', comment: '影响行数', dataType: 'INT' },
              { name: 'execution_time', comment: '执行时间', dataType: 'VARCHAR' }
            ],
            rows: [{
              sql_type: sqlType,
              affected_rows: this.queryResult.affectedRows || this.queryResult.total || 0,
              execution_time: this.queryResult.executionTime || 'N/A'
            }],
            total: 1,
            hasMore: false
          }
        }
        
        // 即使没有执行结果，也提供基本的SQL类型信息
        return {
          columns: [
            { name: 'sql_type', comment: 'SQL类型', dataType: 'VARCHAR' },
            { name: 'sql_statement', comment: 'SQL语句', dataType: 'TEXT' }
          ],
          rows: [{
            sql_type: sqlType,
            sql_statement: this.statement.processed.substring(0, 200) + (this.statement.processed.length > 200 ? '...' : '')
          }],
          total: 1,
          hasMore: false
        }
      }
      
      return null
    },
    
    // 获取SQL类型
    getSQLType() {
      const upperSQL = this.statement.processed.toUpperCase().trim()
      if (upperSQL.startsWith('SELECT')) return 'SELECT'
      if (upperSQL.startsWith('INSERT')) return 'INSERT'
      if (upperSQL.startsWith('UPDATE')) return 'UPDATE'
      if (upperSQL.startsWith('DELETE')) return 'DELETE'
      return 'OTHER'
    }
  }
}
</script>

<style scoped>
.sql-item {
  background: #f9fafb;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  margin-bottom: 15px;
  overflow: hidden;
}

.sql-header {
  background: #f3f4f6;
  padding: 15px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e5e7eb;
}

.sql-index {
  font-weight: 600;
  color: #374151;
  display: flex;
  align-items: center;
  gap: 8px;
}

.sql-index.batch-operation {
  color: #7c3aed;
  font-weight: 700;
}

.batch-badge {
  background: #7c3aed;
  color: white;
  font-size: 10px;
  font-weight: 600;
  padding: 2px 6px;
  border-radius: 12px;
  letter-spacing: 0.5px;
}

.copy-btn {
  background: white;
  color: #4f46e5;
  border: 1px solid #d1d5db;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
  margin-left: 8px;
}

.copy-btn:hover {
  background: #f3f4f6;
  border-color: #9ca3af;
}

.copy-btn.copied {
  background: #10b981;
  color: white;
  border-color: #10b981;
}

.query-btn {
  background: #10b981;
  color: white;
  border: 1px solid #10b981;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
  margin-left: 8px;
}

.query-btn:hover {
  background: #059669;
  border-color: #059669;
}

.ai-btn {
  background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
  color: white;
  border: 1px solid #f59e0b;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
  margin-left: 8px;
}

.ai-btn:hover {
  background: linear-gradient(135deg, #d97706 0%, #b45309 100%);
  border-color: #d97706;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(245, 158, 11, 0.3);
}

.sql-content {
  padding: 20px;
  font-family: 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-all;
  background: #f8fafc;
  border-radius: 4px;
  overflow-x: auto;
}

.sql-content >>> .sql-keyword {
  color: #3b82f6;
  font-weight: 600;
}

.sql-content >>> .sql-string {
  color: #10b981;
}

.sql-content >>> .sql-number {
  color: #f59e0b;
}

.sql-content >>> .sql-comment {
  color: #6b7280;
  font-style: italic;
}

.sql-content >>> .sql-function {
  color: #8b5cf6;
  font-weight: 500;
}

@media (max-width: 768px) {
  .sql-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .sql-header > div {
    margin-top: 8px;
  }
  
  .copy-btn,
  .query-btn,
  .ai-btn {
    font-size: 11px;
    padding: 5px 10px;
  }
}
</style>